# encoding: utf-8
import json
import time

from utils.common_utils import create_chrome_driver_window
from config import settings as env_setting

"""
获取biz.taptap.cn的登录cookies,使用selenium-driver进行抓取
"""


def get_cookies(url, path):
    driver = create_chrome_driver_window()
    # 获取cookie
    driver.get(url)  # 打断点，登陆
    dictCookies = driver.get_cookies()  # 获取cookies
    # 持久化cookie到本地文件
    with open(path, 'w', encoding='utf-8') as f:
        f.write(json.dumps(dictCookies, indent=2, ensure_ascii=False, sort_keys=False))
        f.close()


    # 之后每次运行代码driver.get之前注入cookie
    with open(path, 'r', encoding='utf-8') as fp:
        listCookies = json.load(fp)
        fp.close()
    driver.get(url)

    for cookie in listCookies:
        driver.add_cookie(cookie)
    driver.get(url)

    time.sleep(5)
    driver.refresh()


if __name__ == '__main__':
    # url = "https://biz.taptap.cn"
    # get_cookies(url=url, path=env_setting.TAPTAP_BIZ_COOKIE_PATH)

    url = "https://www.ximalaya.com/"
    get_cookies(url=url, path=env_setting.TAPTAP_DASHBOARD_COOKIE_PATH)

    # driver = create_chrome_driver_window()
    #
    # # 之后每次运行代码driver.get之前注入cookie
    # with open('bilibili_backend_cookies.txt', 'r', encoding='utf-8') as fp:
    #     listCookies = json.load(fp)
    #     fp.close()
    # for cookie in listCookies:
    #     driver.add_cookie(cookie)
    # driver.get("https://cm.bilibili.com/agent/#/customer.account/account")
    # print("get agent url ")
    # page_source = driver.page_source
    # print(page_source)
